package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.Warehouse;
import com.geek.factory.result.Result;
import com.geek.factory.service.IWarehouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 仓库管理控制器
 */
@RestController
@RequestMapping("/warehouse")
@Api(tags = "仓库管理")
@Slf4j
@CrossOrigin
public class WarehouseController {

    @Autowired
    private IWarehouseService warehouseService;

    private final Random random = new Random();

    /**
     * 生成仓库编码
     */
    private String generateWarehouseCodeInternal() {
        String prefix = "W";  // W = Warehouse
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        // 添加3位随机数
        String randomStr = String.format("%03d", random.nextInt(1000));
        return prefix + dateStr + timeStr + randomStr;
    }

    /**
     * 生成唯一的仓库编码(带重试机制)
     */
    private String generateUniqueWarehouseCode() {
        int maxRetries = 3;
        int retryCount = 0;
        
        while (retryCount < maxRetries) {
            String code = generateWarehouseCodeInternal();
            // 检查编码是否已存在
            QueryWrapper<Warehouse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("warehouse_code", code);
            if (warehouseService.count(queryWrapper) == 0) {
                return code;
            }
            retryCount++;
            log.warn("仓库编码 {} 已存在,正在重试生成 ({}/{})", code, retryCount, maxRetries);
        }
        throw new RuntimeException("无法生成唯一的仓库编码,请稍后重试");
    }

    @ApiOperation("生成仓库编码")
    @GetMapping("/generate-code")
    public Result generateWarehouseCode() {
        try {
            String warehouseCode = generateUniqueWarehouseCode();
            Map<String, String> result = new HashMap<>();
            result.put("warehouseCode", warehouseCode);
            return new Result(SuccessConstant.SUCCESS, "生成成功", result);
        } catch (Exception e) {
            log.error("生成仓库编码失败", e);
            return new Result(SuccessConstant.FAIL, "生成失败: " + e.getMessage());
        }
    }

    @ApiOperation("通过ID查询仓库信息")
    @GetMapping("/{warehouseId}")
    public Result findWarehouseById(@ApiParam("仓库ID") @PathVariable("warehouseId") Integer warehouseId) {
        Warehouse warehouse = warehouseService.getById(warehouseId);
        log.info("warehouse: {}", warehouse);
        if (warehouse != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", warehouse);
        }
        return new Result(SuccessConstant.FAIL, "仓库不存在");
    }

    @ApiOperation("新增仓库")
    @PostMapping
    public Result addWarehouse(@RequestBody Warehouse warehouse) {
        try {
            // 如果没有设置仓库编码，自动生成
            if (warehouse.getWarehouseCode() == null || warehouse.getWarehouseCode().trim().isEmpty()) {
                warehouse.setWarehouseCode(generateUniqueWarehouseCode());
            } else {
                // 如果提供了仓库编码,检查是否已存在
                QueryWrapper<Warehouse> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("warehouse_code", warehouse.getWarehouseCode());
                if (warehouseService.count(queryWrapper) > 0) {
                    return new Result(SuccessConstant.FAIL, "仓库编码已存在");
                }
            }

            // 设置默认值
            if (warehouse.getCreatedTime() == null) {
                warehouse.setCreatedTime(LocalDateTime.now());
            }
            if (warehouse.getCreatedBy() == null || warehouse.getCreatedBy().trim().isEmpty()) {
                warehouse.setCreatedBy("admin");
            }

            boolean isSuccess = warehouseService.save(warehouse);
            log.info("新增仓库: {}, 结果: {}", warehouse, isSuccess);
            if (isSuccess) {
                return new Result(SuccessConstant.SUCCESS, "新增成功", warehouse);
            }
            return new Result(SuccessConstant.FAIL, "新增失败");
        } catch (Exception e) {
            log.error("新增仓库失败", e);
            return new Result(SuccessConstant.FAIL, "新增失败: " + e.getMessage());
        }
    }

    @ApiOperation("删除仓库")
    @DeleteMapping("/{warehouseId}")
    public Result deleteWarehouse(@ApiParam("仓库ID") @PathVariable("warehouseId") Integer warehouseId) {
        boolean isSuccess = warehouseService.removeById(warehouseId);
        log.info("删除仓库ID: {}, 结果: {}", warehouseId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    @ApiOperation("修改仓库")
    @PutMapping("/{warehouseId}")
    public Result updateWarehouse(@ApiParam("仓库ID") @PathVariable("warehouseId") Integer warehouseId, @RequestBody Warehouse warehouse) {
        warehouse.setWarehouseId(warehouseId);
        boolean isSuccess = warehouseService.updateById(warehouse);
        log.info("修改仓库: {}, 结果: {}", warehouse, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", warehouse);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("分页查询仓库")
    @GetMapping("/page")
    public Result getWarehousePage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String warehouseName,
            @RequestParam(required = false) String warehouseCode
    ) {
        QueryWrapper<Warehouse> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(warehouseName)) {
            wrapper.like("warehouse_name", warehouseName);
        }
        if (StringUtils.isNotBlank(warehouseCode)) {
            wrapper.like("warehouse_code", warehouseCode);
        }
        wrapper.orderByDesc("created_time");

        Page<Warehouse> page = warehouseService.page(new Page<>(current, size), wrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());
        data.put("pages", page.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("获取所有仓库列表")
    @GetMapping("/list")
    public Result getAllWarehouses() {
        List<Warehouse> warehouses = warehouseService.list();
        return new Result(SuccessConstant.SUCCESS, "查询成功", warehouses);
    }

    @ApiOperation("获取仓库统计数据")
    @GetMapping("/stats")
    public Result getWarehouseStats() {
        try {
            // 获取仓库数量
            long warehouseCount = warehouseService.count();

            Map<String, Object> stats = new HashMap<>();
            stats.put("totalWarehouses", warehouseCount);

            return new Result(SuccessConstant.SUCCESS, "查询成功", stats);
        } catch (Exception e) {
            log.error("获取仓库统计数据失败", e);
            return new Result(SuccessConstant.FAIL, "获取统计数据失败");
        }
    }

}